#include "FileExporter.h"
#include <QFile>
#include <QDir>
#include <QFileInfo>

FileExporter::FileExporter()
{
}

bool FileExporter::exportFiles(const QVector<FileInfo>& files, const QString& exportPath, const QString& prefix, QString& errorMessage, bool deleteOriginal)
{
    QDir dir(exportPath);
    if (!dir.exists()) {
        if (!dir.mkpath(".")) {
            errorMessage = QString("无法创建导出目录: %1").arg(exportPath);
            return false;
        }
    }

    int count = 1;
    for (const FileInfo& file : files) {
        QString sourcePath = file.filePath;
        QFileInfo sourceFileInfo(sourcePath);
        
        if (!sourceFileInfo.exists()) {
            errorMessage = QString("源文件不存在: %1").arg(sourcePath);
            return false;
        }
        
        if (!sourceFileInfo.isReadable()) {
            errorMessage = QString("无法读取源文件: %1").arg(sourcePath);
            return false;
        }
        
        QString extension = sourceFileInfo.suffix();
        QString destPath = QString("%1/%2_%3.%4").arg(exportPath).arg(prefix).arg(count, 3, 10, QChar('0')).arg(extension);

        if (QFile::exists(destPath)) {
            errorMessage = QString("目标文件已存在: %1").arg(destPath);
            return false;
        }

        if (!QFile::copy(sourcePath, destPath)) {
            errorMessage = QString("复制文件失败: 从 %1 到 %2").arg(sourcePath).arg(destPath);
            return false;
        }

        if (deleteOriginal) {
            if (!QFile::remove(sourcePath)) {
                errorMessage = QString("删除原文件失败: %1").arg(sourcePath);
                return false;
            }
        }

        count++;
    }

    return true;
}
